package com.echo.week02.classLoader;

import java.io.*;

/**
 * @Author echo
 * @Description 自定义的classLoader
 * @Date 2023/9/24.
 * @Version 1.0
 */
public class HeroClassLoader extends ClassLoader{

    private String classPath ;


    public HeroClassLoader(String classPath){
        this.classPath = classPath;
    }
    /**
     * Finds the class with the specified <a href="#name">binary name</a>.
     * This method should be overridden by class loader implementations that
     * follow the delegation model for loading classes, and will be invoked by
     * the {@link #loadClass <tt>loadClass</tt>} method after checking the
     * parent class loader for the requested class.  The default implementation
     * throws a <tt>ClassNotFoundException</tt>.
     *
     * @param name The <a href="#name">binary name</a> of the class
     * @return The resulting <tt>Class</tt> object
     * @throws ClassNotFoundException If the class could not be found
     * @since 1.2
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classData = getData(name);
            if (classData!=null){
                return defineClass(name,classData,0,classData.length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    /**
     * 加载类的字节码数据
     * @param className
     * @return
     * @throws IOException
     */
    private byte[] getData(String className) throws IOException {
        String path = classPath + File.pathSeparator + className.replace(".", File.pathSeparator) + ".class";
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len = 0;
            while((len =fileInputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
            return outputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
